from flask import Flask, render_template, url_for, session, redirect, request
from . import login
from .forms import LoginForm
from app.models import User, Article, Oplog, db
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
from io import BytesIO
import base64
import datetime

code1 = '1234'


def validate_picture():
    total = '012345789'
    # 图片大小130 x 50
    width = 130
    heighth = 50
    # 先生成一个新图片对象
    im = Image.new('RGB', (width, heighth), 'white')
    # 设置字体
    font = ImageFont.truetype("SitkaZ.ttc", 30)
    # 创建draw对象
    draw = ImageDraw.Draw(im)
    str = ''
    # 输出每一个文字
    for item in range(4):
        text = random.choice(total)
        str += text
        draw.text((-3 + random.randint(3, 7) + 25 * item, -3 + random.randint(2, 7)), text=text, fill='black',
                  font=font)

    # 划几根干扰线
    for num in range(5):
        x1 = random.randint(0, int(width / 2))
        y1 = random.randint(0, int(heighth / 2))
        x2 = random.randint(0, width)
        y2 = random.randint(int(heighth / 2), heighth)
        draw.line(((x1, y1), (x2, y2)), fill='black', width=1)

    # 加上滤镜
    im = im.filter(ImageFilter.FIND_EDGES)
    print(str)
    return im, str


# 生成验证码实例的函数
def run_code():
    # 生成验证码，image为验证码图片，code为验证码文本
    image, code = validate_picture()

    # 将验证码图片以二进制形式写入在内存中，防止将图片都放在文件夹中，占用大量磁盘
    buf = BytesIO()
    image.save(buf, 'jpeg')
    buf_str = buf.getvalue()

    data = str(base64.b64encode(buf_str))[1:].strip("'")  # 将验证码转换为base64格式
    # session['code'] = code  #将验证码文本存入session，做用户登录认证时可用
    return data, code


@login.route('/', methods=('GET', 'POST'))
def login():
    print('login GRT 函数开始执行')
    global code1
    users = {}
    form = LoginForm()
    if request.method == 'POST':
        print(form.validate_on_submit())
        if form.validate_on_submit():
            username = form.data['user']
            password = form.data['pwd']
            veri = form.data['veri']
            u = User.query.filter_by(user_name=username).first()
            p = u.user_password
            if u is not None:
                if p == password:
                    print('login POST 函数开始执行')
                    if veri == code1:
                        session['username'] = u.user_name
                        arts = Article.query.order_by(Article.arc_click).all()
                        for item in arts:
                            users[item] = User.query.filter_by(user_name=item.arc_author).first()
                        print("'username' in session: = ", 'username' in session)
                        if 'username' in session:
                            print(session['username'])
                            if session['username'] == None:
                                mylogin = '登录'
                                login = '/login'
                                publish = '/publish'
                                return render_template('index.html', users=users, mylogin=mylogin, login=login,
                                                       publish=publish)
                            else:
                                opuser = session['username']
                                op1 = "LOG IN"
                                ip = request.remote_addr
                                date = datetime.datetime.now()
                                OPT = Oplog(op_user=opuser, op=op1, IP=ip, op_date=date)
                                db.session.add(OPT)
                                db.session.commit()
                                return redirect(url_for('index.index'))
                                # return render_template('index.html', users=users, login=login, mylogin=mylogin,
                                #                        publish=publish)
                        else:
                            mylogin = '登录'
                            login = '/login'
                            publish = '/publish'
                            return render_template('index.html', users=users, mylogin=mylogin, login=login, publish=publish)
                    else:
                        return "验证码错误"
                else:
                    return '密码错误!'
            else:
                return '用户名错误!'
    data, code = run_code()
    code1 = code
    return render_template('login.html', form=form, img_stream=data)


